{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# {class}`~tensorflow.Graph`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "{class}`~tensorflow.Graph` 被 {class}`~tensorflow.function` 用来表示函数的计算过程。每个图包含一组 {class}`~tensorflow.Operation` 对象，这些对象代表计算单元；以及 {class}`~tensorflow.Tensor` 对象，这些对象代表在算子之间流动的数据单元。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import set_env"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 直接使用图（已弃用）\n",
    "可以直接构建和使用 {class}`~tensorflow.Graph`，而无需 {class}`~tensorflow.function`，这是在 TensorFlow 1 中的要求。但这种做法已被弃用，建议改用 {class}`~tensorflow.function`。如果直接使用 {class}`~tensorflow.Graph`，还需要其他已弃用的 TensorFlow 1 类来执行图，例如 `tf.compat.v1.Session`。\n",
    "\n",
    "可以使用 {meth}`~tensorflow.Graph.as_default` 上下文管理器注册默认图。然后，算子将被添加到 {class}`~tensorflow.Graph` 中而不是立即执行。例如："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<tf.Tensor 'mul:0' shape=() dtype=float32>"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "\n",
    "g = tf.Graph()\n",
    "with g.as_default():\n",
    "    # 在 `g` 中定义算子和张量。\n",
    "    c = tf.constant(30.0)\n",
    "    assert c.graph is g\n",
    "    d = c * c\n",
    "\n",
    "d"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "g.building_function # 仅当此图表示函数时返回 `True`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 返回此图已知的集合的名称\n",
    "g.collections"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "g.finalized # 如果此图已经被最终确定，则为 `True`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "计算图的 `GraphDef` 版本信息。（有关每个版本含义的详细信息，请参阅 [GraphDef](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/graph.proto)）。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "producer: 1882"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "g.graph_def_versions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[<tf.Operation 'Const' type=Const>, <tf.Operation 'mul' type=Mul>]"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "g.operations # 算子"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "node {\n",
       "  name: \"Const\"\n",
       "  op: \"Const\"\n",
       "  attr {\n",
       "    key: \"value\"\n",
       "    value {\n",
       "      tensor {\n",
       "        dtype: DT_FLOAT\n",
       "        tensor_shape {\n",
       "        }\n",
       "        float_val: 30\n",
       "      }\n",
       "    }\n",
       "  }\n",
       "  attr {\n",
       "    key: \"dtype\"\n",
       "    value {\n",
       "      type: DT_FLOAT\n",
       "    }\n",
       "  }\n",
       "}\n",
       "node {\n",
       "  name: \"mul\"\n",
       "  op: \"Mul\"\n",
       "  input: \"Const\"\n",
       "  input: \"Const\"\n",
       "  attr {\n",
       "    key: \"T\"\n",
       "    value {\n",
       "      type: DT_FLOAT\n",
       "    }\n",
       "  }\n",
       "}\n",
       "versions {\n",
       "  producer: 1882\n",
       "}"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "g.as_graph_def() "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a + b = 7\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "\n",
    "g = tf.Graph()\n",
    "with g.as_default():\n",
    "    # 创建常量算子\n",
    "    a = tf.constant(3)\n",
    "    b = tf.constant(4)\n",
    "    # 创建加法算子\n",
    "    c = a + b\n",
    "    # 启动会话\n",
    "    with tf.compat.v1.Session() as sess:\n",
    "        # 运行计算图并获取结果\n",
    "        result = sess.run(c)\n",
    "        print(f\"a + b = {result}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a + b = 3\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "\n",
    "g = tf.Graph()\n",
    "with g.as_default():\n",
    "    # 创建常量算子\n",
    "    a = tf.constant(3)\n",
    "    b = tf.Variable(0, dtype=tf.int32)  # 初始化变量 b，并指定数据类型为int32\n",
    "    # 创建加法算子\n",
    "    c = a + b\n",
    "    # 启动会话\n",
    "    with tf.compat.v1.Session() as sess:\n",
    "        # 初始化所有变量\n",
    "        sess.run(tf.compat.v1.global_variables_initializer())\n",
    "        # 运行计算图并获取结果\n",
    "        result = sess.run(c, feed_dict={b: 4})\n",
    "        print(f\"a + b = {result}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "xxx",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
